#include "head.h"

int fun_cd(MYSQL *mysql,char *user_id,char *path,char *curr_path, pool_t *pool){
    char sql[1024] = {0};
    char buf[1024] = {0};
    char temp_path[1024] = {0};
    strcpy(buf,path);
    MYSQL_RES *result; 
    MYSQL_ROW row;
    int userid = atoi(user_id);

    char *saveptr;//保存strtok_r函数的上下文信息
    char *p=strtok_r(buf,"/",&saveptr);
    int state=1;//1表示正常退出，0表示异常退出
    pthread_mutex_lock(&pool->sql_lock);
    while(p!=NULL){
        if(state == 0){
            break;
        }
        if(strcmp(p,"..") == 0){
            bzero(sql,sizeof(sql));
            sprintf(sql,"select father_id from file_table where user_id = %d and path = '%s'",userid,curr_path);
            if (mysql_query(mysql,sql)) {
                printf("%s\n", mysql_error(mysql));
                return 1;
            }
            result = mysql_store_result(mysql);     

            row = mysql_fetch_row(result);
            char *pre_id = row[0];
            int fatherid = atoi(pre_id);
            printf("fatherid:%d\n",fatherid);
            if(fatherid == -1){
                printf("已经是根目录\n");
                state = 0;
                continue;
            }
            mysql_free_result(result);

            bzero(sql,sizeof(sql));
            sprintf(sql,"select path from file_table where user_id = %d and file_id = %d ",userid,fatherid);
            if (mysql_query(mysql,sql)) {
                printf("%s\n", mysql_error(mysql));
                return 1;
            }
            result = mysql_store_result(mysql);
            row = mysql_fetch_row(result);
            printf("%s\n",row[0]);
            curr_path = row[0];
            mysql_free_result(result);
        }else{
            bzero(sql,sizeof(sql));
            sprintf(sql,"select file_name from file_table  where user_id = %d and file_properties = 1  and file_name !='/1' and flag = 1",userid);
            if (mysql_query(mysql,sql)) {
                printf("%s\n", mysql_error(mysql));
                return 1;
            }
            result = mysql_store_result(mysql);    
            while ((row = mysql_fetch_row(result))) {
                if(strcmp(p,row[0]) == 0){
                    state = 1;
                    break;
                }else{
                    state = 0;
                }
            }
            mysql_free_result(result);
        }
        p = strtok_r(NULL,"/",&saveptr);
    }
    pthread_mutex_unlock(&pool->sql_lock);
    if(state==1){//cd执行成功
        printf("cd执行成功\n");
        return 1;
    }else{//cd执行失败
        printf("cd执行失败\n");
        return 0;
    }
    return 1;
}


